package cx.ath.skyflyer.chart;

import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;

/**
 *
 * @author Ahti Legonkov
 */
public class VerticalAxis {

    public VerticalAxis(Rectangle screenRect) {
        this.screen = screenRect;
    }

    public void setUnit(String unit) {
        this.unit = unit;
    }
    
    public void setTicks(int n) {
        ticks = n;
    }

    public void setMax(double max) {
        this.max = max;
    }

    public void setMin(double min) {
        this.min = min;
    }

    private void adjustMinMax() {
        final double diff = max-min;
        if (diff < 10) {
            final double mid = (max+min)/2;
            max = mid + 5;
            min = mid - 5;
        }
    }

    public void setMargins(Margins m) {
        this.margins = m;
    }

    public void draw(Graphics g) {
        int x = margins.left;

        g.setColor(0);
        g.setStrokeStyle(Graphics.SOLID);

        int arrowSize = 6;

        g.setColor(0);

        // draw the axis unit label
        g.setFont(Font.getFont(Font.FACE_MONOSPACE, Font.STYLE_PLAIN, Font.SIZE_SMALL));
        g.drawString(unit, x + arrowSize/2, 0, Graphics.LEFT | Graphics.TOP);

        // the axis
        g.drawLine(x, screen.top, x, screen.bottom);

        // arrow head
        g.drawLine(x-arrowSize/2, arrowSize, x, 0);
        g.drawLine(x+arrowSize/2, arrowSize, x, 0);

        if (max-min < 10)
            adjustMinMax();

        // the ticks
        int pixelStep = (screen.height() - margins.bottom - arrowSize)/ ticks;
        int valueStep = (int)((max - min) / ticks);
        if (valueStep == 0)
            valueStep = 1;

        // the tick labels
        for (int i = screen.bottom-margins.bottom, value = (int)min; i > arrowSize; i -= pixelStep, value += valueStep) {
            g.drawLine(x, i, x+3, i);

            String strValue = value + "";
            g.drawString(strValue, x, i, Graphics.RIGHT | Graphics.BASELINE);
        }
    }

    private double min = 0;
    private double max = 100;
    private int ticks = 2;
    private String unit = "m/s";
    private Margins margins = new Margins();
    private Rectangle screen;
}
